#include "client.h"
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <errno.h>
#include "common_defs.h"

using namespace std;

#define NUM_OF_ARGS			(4)
#define MIN_PORT_NUM		(1025)
#define MAX_PORT_NUM		(65535)
#define MAX_CLIENT_NAME_LEN	(30)

int main(int argc,char** argv)
{
	Client* 	client;
	result_t 	result;
	int 		port;
	string		client_name,server_address;

	// Argument validation
	if ( NUM_OF_ARGS != argc)
	{
		cerr << "Usage: " << argv[0] <<  " <CLIENT NAME> <SERVER ADDRESS> <SERVER PORT>"<< endl;
		return EXIT_FAILURE;
	}

	// Get client name and verify its legality
	client_name = argv[1];
	if(client_name.length() > MAX_CLIENT_NAME_LEN)
	{
		PRINT_ERROR("Client name is longer than 30 characters");
		exit(1);
	}
	if( client_name.find(" ") != string::npos || client_name.find("@") != string::npos )
	{
		PRINT_ERROR("Client name contains invalid characters");
		exit(1);
	}

	// Get server address and validate it.
	server_address = argv[2];

	port = atoi( argv[3] );
	if ( ! port || port < MIN_PORT_NUM || port > MAX_PORT_NUM )
	{
		cerr << "Invalid port number" << port  <<endl;
		return EXIT_FAILURE;
	}

	client = new Client(client_name, server_address ,port);

	result = client->start_client();

	delete client;

	return ( OPERATION_SUCCESS == result )? EXIT_SUCCESS : EXIT_FAILURE;
}
